<?php
class GoodsDataModel extends Model {
	public $table = 'goods';
	private $cid;
	public function __init() {
		$this -> cid = Q('cid', 0, 'intval');
	}

	//前台商品列表页获得商品数据
	public function getAll() {
		//搜索属性id
		$s = explode('-', $_GET['s']);
		//移除属性值为0的
		$avid = array();
		foreach ($s as $v) {
			if (!$v)
				continue;
			$avid[] = $v;
		}
		if (empty($avid)) {//s属性没有值，没有指定筛选条件
			$map['cid'] = array('EQ', $this -> cid);
			//获得该栏目下商品
			$count = $this -> where($map) -> count();
			//统计、用于分页使用
			$page = new Page($count);
			$goods = $this -> where($map) -> limit($page -> limit()) -> all();
			return array('goods' => $goods, 'page' => $page -> show());
		} else {
			$sql = " FROM jz_goods as goods JOIN ";
			for ($i = 0; $i < count($avid); $i++) {
				$sql .= "jz_goods_attr_list as g{$i} JOIN ";
			}
			$sql = substr($sql, 0, -5).' ON ';
			//关联关系ON
			for ($i = 0; $i < count($avid); $i++) {
				$n=$i+1;
				if($n>=count($avid))break;
				$sql .= "g{$i}.gid=g{$n}.gid AND ";
			}
			$sql=$sql." goods.gid=g{$i}.gid ".' WHERE ';
			//属性筛选条件
			for ($i = 0; $i < count($avid); $i++) {
				$sql .= "g{$i}.avid=" . $avid[$i] . ' AND ';
			}
			$sql .= " goods.cid={$this->cid} GROUP BY goods.gid	";
			$countSql = "select count(*) as c ".$sql;
			$count= M()->query($countSql);
			$page = new Page($count[0]['c']);
			$sql="select * ".$sql.' LIMIT '.$page->limit();
			$goods = M()->query($sql);
			return array('goods' => $goods, 'page' => $page -> show());
		}

	}

	//商品列表页用于搜索商品时的属性列表
	public function getAttrList() {
		//商品类型id
		$gtid = M('category') -> where("cid={$this->cid}") -> getField('gtid');
		//获得属性
		$attr = M("goods_attr") -> where('gtid=' . $gtid) -> all();
		foreach ($attr as $id => $a) {
			$attr[$id]['_value'] = M('goods_attr_value') -> where('attr_aid=' . $a['aid']) -> all();
		} 
		return $attr;
	}

	//获得栏目所属类型有多少个属性
	public function getAttrNum() {
		$gtid = M('category') -> where("cid={$this->cid}") -> getField('gtid');
		//获得属性
		return M("goods_attr") -> where("show_type <>'text'") -> where('gtid=' . $gtid) -> count();
	}

}
